package net.test.action.admin;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import net.test.action.admin.BaseAdminAction.Status;
import net.test.entity.Admin;
import net.test.entity.Role;
import net.test.service.RoleService;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.BeanUtils;

import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

@ParentPackage("admin")
public class RoleAction extends BaseAdminAction{

	private static final long serialVersionUID = 3011872273406916129L;
	
	private Role role;
	
	@Resource(name="roleServiceImpl")
	private RoleService roleService;
	
	//列表
	public String list(){
		pager=roleService.findPageByRole(pager,role);
		
		return LIST;
	}

	
	//添加
	public String add(){
		
		return INPUT;
	}
	
	//编辑
	public String edit(){
		role=roleService.get(id);
		
		return INPUT;
	}
	
	//保存
	@Validations(
		requiredStrings = { 
			@RequiredStringValidator(fieldName = "role.name", message = "角色名称不允许为空!")
		},
		requiredFields = {
			@RequiredFieldValidator(fieldName = "role.authorityList", message = "角色权限不允许为空!")
		}
	)
	@InputConfig(resultName = "error")
	public String save(){
		List<String> authorityList = role.getAuthorityList();
		authorityList.add(Role.ROLE_BASE);
		role.setAuthorityList(authorityList);
		roleService.save(role);
		return ajax(Status.success,"角色添加成功！","role!list.shtml");
	}
	
	//更新
	@Validations(
		requiredStrings = { 
			@RequiredStringValidator(fieldName = "role.name", message = "角色名称不允许为空!")
		},
		requiredFields = {
			@RequiredFieldValidator(fieldName = "role.authorityList", message = "角色权限不允许为空!")
		}
	)
	@InputConfig(resultName = "error")
	public String update(){
		try{
			Role persistent = roleService.load(id);
			List<String> authorityList = role.getAuthorityList();
			authorityList.add(Role.ROLE_BASE);
			role.setAuthorityList(authorityList);
			BeanUtils.copyProperties(role, persistent, new String[] {"id", "createDate", "modifyDate", "adminSet"});
			roleService.update(persistent);
		}catch(Exception e){
			e.printStackTrace();
		}
		return ajax(Status.success,"角色修改成功！","role!list.shtml");
	}
	
	//删除
	public String delete(){
		StringBuffer logInfoBuffer = new StringBuffer();
		for (String id : ids) {
			Role role = roleService.load(id);
			Set<Admin> adminSet = role.getAdminSet();
			if (adminSet != null && adminSet.size() > 0) {
				return ajax(Status.error, "角色[" + role.getName() + "]下存在管理员,删除失败!");
			}
			logInfoBuffer.append(","+role.getName());
		}
		roleService.delete(ids);
		return ajax(Status.success,"删除角色成功！");
	}


	public Role getRole() {
		return role;
	}


	public void setRole(Role role) {
		this.role = role;
	}
	
	
}
